package com.clear.honghefinance.biz.modules.system.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.clear.honghefinance.biz.modules.system.tenant.constant.TenantSysConfigKeyConstant;
import com.clear.honghefinance.biz.modules.system.tenant.domain.entity.TenantSysConfig;
import com.clear.honghefinance.biz.modules.system.member.domain.vo.AdminDTO;
import com.clear.honghefinance.biz.modules.system.tenant.domain.vo.SubjectCodeLengthConfigVO;
import com.clear.honghefinance.biz.modules.system.tenant.mapper.TenantSysConfigMapper;
import com.clear.honghefinance.biz.modules.system.tenant.service.ITenantSysConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clear.honghefinance.common.exception.BizException;
import com.clear.honghefinance.common.service.TokenService;
import com.clear.honghefinance.common.util.GsonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 租户系统配置 服务实现类
 * </p>
 *
 * @author 程序员clear
 * @since 2024-08-25
 */
@Service
@Slf4j
public class TenantSysConfigServiceImpl extends ServiceImpl<TenantSysConfigMapper, TenantSysConfig> implements ITenantSysConfigService {

    @Resource
    private TokenService<AdminDTO> tokenService;

    /**
     * 获取科目长度配置
     *
     * @return
     */
    @Override
    public SubjectCodeLengthConfigVO getSubjectCodeLengthConfig() {
        LambdaQueryWrapper<TenantSysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TenantSysConfig::getDelFlag, false)
                .eq(TenantSysConfig::getConfigKey, TenantSysConfigKeyConstant.SUBJECT_CODE_LENGTH_CONFIG)
                .eq(TenantSysConfig::getTenantId, tokenService.getThreadLocalTenantId())
                .select(TenantSysConfig::getConfigValue);

        TenantSysConfig tenantSysConfig = this.getOne(queryWrapper);
        if (tenantSysConfig == null) {
            throw new BizException("科目编码长度配置为空");
        }
        try {
            return GsonTool.fromJson(tenantSysConfig.getConfigValue(), SubjectCodeLengthConfigVO.class);
        } catch (Exception ex) {
            throw new BizException("解析科目编码长度配置异常");
        }
    }

}
